<template>
  <div class="casecontiner" v-if="!caseimgshow">
    <!-- 头部 -->
    <div class="casetop" v-if="caseTypeshow">
      <div class="casename">病例学习</div>
      <div class="caseicon" @click="goimessage">
        <img src="@/assets/images/imessge.png" alt="" />
        消息
      </div>
    </div>
    <!-- 病例分类 -->
    <div class="casemain beautifulScroll" v-if="caseTypeshow">
      <div
        class="caseitem"
        v-for="item in renderData"
        :key="item.caseTypeId"
        @click="casefn(item)"
      >
        <div class="caseitemimg">
          <img :src="`${base + item.url}`" alt=""
        /></div>
        <div class="caseitemname">{{ item.caseTypeName }}</div>
      </div>
    </div>
    <!-- 分类 - 病例列表 -->
    <div class="casetop" v-if="!caseTypeshow">
      <div class="caseback" @click="caseTypeshow = true"
        ><van-icon name="arrow-left"
      /></div>
      <div class="casename"
        >病例学习 - {{ caseTypeName }}
        <div class="casetotal">{{ casetotal }}</div></div
      >
      <div class="selcetboximg caseselect" @click="visible = true">
        <img src="@/assets/images/selcetboximg.png" alt="" />
      </div>
    </div>
    <!-- 搜索 -->
    <div class="searchbox" v-if="!caseTypeshow">
      <van-search
        v-model="caseName"
        shape="round"
        background="transparent"
        placeholder="请输入搜索关键词"
        @clear="reset"
        class="caseserbox"
      >
        <template #right-icon>
          <div @click="onRefresh()" style="color: black">搜索&nbsp;&nbsp;</div>
        </template>
      </van-search>
      <div class="restbox" @click="reset">重 置</div></div
    >

    <!-- 搜索结束 -->
    <!-- 内容 -->
    <div
      class="casemains beautifulScroll"
      @scroll="handleScroll"
      ref="scrollContainer"
      v-if="caselist.length > 0 && !caseTypeshow"
    >
      <!-- 下拉刷新提示 -->
      <div v-if="isRefreshing" class="refreshing">正在刷新...</div>
      <!-- 展示数据 -->
      <div
        v-for="(item, index) in caselist"
        class="caselistitem"
        @click="gocase(item)"
      >
        <div class="caselistimg">
          <div class="caseimgqb">{{ index + 1 }}</div>
          <img :src="`${base + item.url}`" alt="" />
        </div>
        <div class="caselistmain">
          <div class="caselisttop">
            <div> {{ item.caseName }}</div>

            <div
              class="casefavorite"
              v-if="item.favoriteStatus == 0"
              @click.stop="favoriteDelfn(item.favoriteFolderId)"
            >
              <img src="@/assets/images/tpitemscac.png" alt="" />
            </div>
            <div class="casefavorite" v-else @click.stop="favoriteAddfn(item)">
              <img src="@/assets/images/tpitemsc.png" alt="" />
            </div>
          </div>
          <div class="caselistdes">{{ item.situation }}</div>
        </div>
      </div>
      <!-- 触底加载提示 -->
      <div v-if="isLoading" class="loading">加载更多...</div>
      <div v-if="finished" class="loading">没有数据了！</div>
    </div>

    <div class="casemains" v-else> <div class="loadingd">暂无数据</div> </div>

    <!-- 抽屉筛选 -->

    <div class="ctfiexd" v-if="visible">
      <div class="ctmain">
        <div class="cttop"
          >病例分类

          <img
            src="@/assets/images/closenew.png"
            alt=""
            class="closenew"
            @click="visible = false"
          />
        </div>
        <div class="ctbox">
          <div
            @click="casefn(item)"
            class="ctitem"
            :class="caseTypeId == item.caseTypeId ? 'active' : ''"
            v-for="item in renderData"
            :key="item.caseTypeId"
            >{{ item.caseTypeName }}
          </div>
        </div>
      </div>
    </div>
    <!-- 分类 - 病例列表完成 -->
    <!-- 病例详情 病例图片展示 -->

    <!-- tabbar -->
    <Tabbar :active="2" />
  </div>
  <div v-if="caseimgshow">
    <Caseimg
      @goback="goback"
      :imgsrc="imgsrc"
      :situation="situation"
      :imgFeatures="imgFeatures"
      :diagnosticConclusion="diagnosticConclusion"
      :caseId="caseId"
    />
  </div>
</template>

<script lang="ts" setup>
  import Tabbar from '../tabbar/tabbar.vue';
  import {
    caseList,
    typeList,
    favoriteAdd,
    caseDetails,
    favoriteDel,
    caserecordAdd,
  } from '@/api/case';
  import { Pagination } from '@/types/global';
  import { showFailToast, showSuccessToast } from 'vant';
  import { reactive, ref, onMounted, onBeforeUnmount } from 'vue';
  import { storeToRefs } from 'pinia';
  import { useUserStore } from '@/store';
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  const studentId = ref(userdata.studentId.value);
  const renderData = ref([]); // 渲染的数据列表
  import { useRouter } from 'vue-router';
  import Caseimg from './caseimg.vue';
  const router = useRouter();
  const base = ref((window as any).config.VUE_APP_IMG_API);
  const basePagination: Pagination = {
    current: 1,
    pageSize: 6,
    total: 0,
  };

  const pagination = reactive({ ...basePagination });
  // 定义分类展示
  const caseTypeshow = ref(true);
  const casefn = (item: any) => {
    // console.log('根据病例类型查询病例列表', item);

    caseTypeId.value = item.caseTypeId;
    caseTypeName.value = item.caseTypeName;
    caseTypeshow.value = false;
    onRefresh();
  };
  // 加入收藏
  const favoriteAddfn = (item: any) => {
    favoriteAdd({
      studentId: studentId.value,
      caseAtlasId: item.caseId,
      status: 0,
    }).then((res: any) => {
      if (res.code == 200) {
        showSuccessToast('收藏成功');
        onRefresh();
      } else {
        showFailToast('收藏失败');
      }
    });
  };
  // 取消收藏 favoriteDelfn
  const favoriteDelfn = (item: any) => {
    favoriteDel({
      favoriteFolderIds: item,
    }).then((res: any) => {
      if (res.code == 200) {
        showSuccessToast('取消成功');
        onRefresh();
      } else {
        showFailToast('取消失败');
      }
    });
  };

  // 暂存病例类型
  const caseTypeId = ref(5);
  const caseTypeName = ref('儿科');
  // 暂存病例名称
  const caseName = ref();

  // 病例列表
  const caselist = ref([]);
  // 病例统计
  const casetotal = ref(0);

  // 病例分类
  const fetchDatas = async () => {
    try {
      const res = await typeList({
        pageNum: 1,
        pageSize: 99,
      });
      const newData = res.data.list || [];

      renderData.value = newData; // 刷新时替换数据
    } finally {
    }
  };
  // fetchData();
  fetchDatas();
  // 病例列表
  const fetchData = async (isRefresh = false) => {
    try {
      const res = await caseList({
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        caseTypeId: caseTypeId.value,
        caseName: caseName.value,
        studentId: studentId.value,
      });
      const newData = res.data.list || [];
      if (isRefresh) {
        caselist.value = newData; // 刷新时替换数据
      } else {
        caselist.value = [...caselist.value, ...newData]; // 加载更多时追加数据
      }
      casetotal.value = res.data.total;
      finished.value = caselist.value.length >= res.data.total; // 检查是否加载完成
    } finally {
      // console.log('加载完成了吗', loading.value);
    }
  };
  fetchData();
  // 下拉刷新逻辑
  const onRefresh = async () => {
    pagination.current = 1; // 重置页码
    await fetchData(true); // 刷新数据
    isRefreshing.value = false;
  };

  // 触底加载逻辑
  const onLoadMore = async () => {
    pagination.current += 1;
    console.log('触底');
    await fetchData(); // 加载更多数据
    isLoading.value = false;
  };

  // 去消息列表
  const goimessage = () => {
    router.push({
      name: 'outbox',
    });
  };
  // 病例筛选列表
  const visible = ref(false);

  //  滚动判断
  const scrollContainer = ref<HTMLElement | null>(null);
  const isRefreshing = ref(false);
  const isLoading = ref(false);
  const finished = ref(false);
  let startY = 0; // 记录触摸开始的位置
  let startX = 0; // 记录触摸开始的横向位置
  let isVerticalScroll = false; // 是否为垂直滚动

  // 下拉刷新处理
  const handleTouchStart = (event: TouchEvent) => {
    startY = event.touches[0].clientY;
    startX = event.touches[0].clientX;
    isVerticalScroll = false; // 重置滚动方向
  };

  let debounceTimeout: ReturnType<typeof setTimeout>;

  const handleTouchMove = (event: TouchEvent) => {
    const moveY = event.touches[0].clientY;
    const moveX = event.touches[0].clientX;
    const diffY = Math.abs(moveY - startY);
    const diffX = Math.abs(moveX - startX);

    // 判断是否为垂直滚动（如果垂直位移大于水平位移）
    if (!isVerticalScroll && diffY > diffX) {
      isVerticalScroll = true;
    }

    if (!isVerticalScroll) {
      // 如果不是垂直滚动，直接返回
      return;
    }

    if (scrollContainer.value && scrollContainer.value.scrollTop > 0) {
      return; // 如果不是在顶部，则不处理下拉刷新
    }
    clearTimeout(debounceTimeout); // 清除上一次的定时器
    debounceTimeout = setTimeout(() => {
      const moveY = event.touches[0].clientY;
      if (moveY - startY > 50 && !isRefreshing.value) {
        // 判断下拉超过50px
        isRefreshing.value = true;
        onRefresh();
      }
    }, 300); // 防抖：300ms
  };

  const handleTouchEnd = () => {
    startY = 0; // 清除触摸开始位置
    startX = 0; // 清除横向触摸开始位置

    if (isRefreshing.value) {
      // 可能在触摸结束时再做一些处理，比如清理动画、提示隐藏等
      console.log('刷新已完成');
    }
  };

  // 触底加载处理
  let lastScrollTime = 0;

  const handleScroll = (event: Event) => {
    if (isRefreshing.value) return; // 正在刷新时，不触发触底加载
    const now = Date.now();
    if (now - lastScrollTime > 300) {
      // 节流：每 300ms 执行一次
      lastScrollTime = now;
      const container = event.target as HTMLElement;
      if (
        container.scrollTop + container.clientHeight >=
          container.scrollHeight - 100 &&
        !isLoading.value
      ) {
        if (finished.value) return;
        isLoading.value = true;
        console.log('触底了');
        onLoadMore();
      }
    }
  };

  // 绑定触摸事件
  const bindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener('touchstart', handleTouchStart);
      scrollContainer.value.addEventListener('touchmove', handleTouchMove);
      scrollContainer.value.addEventListener('touchend', handleTouchEnd);
    }
  };

  // 清除触摸事件
  const unbindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.removeEventListener('touchstart', handleTouchStart);
      scrollContainer.value.removeEventListener('touchmove', handleTouchMove);
      scrollContainer.value.removeEventListener('touchend', handleTouchEnd);
    }
  };

  // 生命周期钩子：组件挂载时绑定事件
  onMounted(() => {
    bindTouchEvents();
  });

  // 生命周期钩子：组件卸载时清除事件
  onBeforeUnmount(() => {
    unbindTouchEvents();
  });
  // 滚动判断逻辑完成

  // 清空搜撒
  const reset = () => {
    caseName.value = '';
    onRefresh();
  };
  const situation = ref();
  const imgFeatures = ref();
  const diagnosticConclusion = ref();
  const caseId = ref();
  // 病例详情 situation
  const gocase = (item: any) => {
    caserecordAdd({
      studentId: studentId.value,
      caseId: item.caseId,
    }).then((res: any) => {});
    caseId.value = item.caseId;
    caseDetails({
      studentId: studentId.value,
      caseId: item.caseId,
    }).then((res: any) => {
      if (res.code == 200) {
        console.log('查询成功', res.data);
        imgsrc.value = res.data.imgList;
        situation.value = res.data.situation;
        imgFeatures.value = res.data.imgFeatures;
        diagnosticConclusion.value = res.data.diagnosticConclusion;
        caseimgshow.value = true;
      }
    });
  };

  // go
  const caseimgshow = ref(false);
  const goback = () => {
    caseimgshow.value = false;
  };

  const imgsrc = ref();
  // 判断是否 来自收藏夹
  import { useRoute } from 'vue-router';

  const route = useRoute();
  if (route.query.caseAtlasId) {
    caseId.value = route.query.caseAtlasId;
    caseDetails({
      studentId: studentId.value,
      caseId: caseId.value,
    }).then((res: any) => {
      if (res.code == 200) {
        console.log('查询成功', res.data);
        imgsrc.value = res.data.imgList;
        situation.value = res.data.situation;
        imgFeatures.value = res.data.imgFeatures;
        diagnosticConclusion.value = res.data.diagnosticConclusion;
        caseimgshow.value = true;
      }
    });
  }
</script>

<style scoped>
  .caseserbox {
    width: 600px;
  }
  .searchbox {
    display: flex;
    align-items: center;
  }
  .restbox {
    width: 114px;
    height: 70px;
    background: #5f6d7c;
    border-radius: 61px 61px 61px 61px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;
    color: #fff;
  }
  .casecontiner {
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg, #5f6d7c 0%, #f4f4f4 25%);
  }
  .casetop {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    font-size: 32px;
    color: #ffff;
    position: relative;
    top: 0px;
    left: 0;
  }
  .casemain {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;
    height: 100%;
    padding-bottom: 250px;
  }

  .caseitemimg {
    width: 293px;
    height: 210px;
    overflow: hidden;
  }
  .caseitemimg img {
    width: 293px;
    height: 210px;
  }
  .caseitem {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 325px;
    height: 300px;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    font-size: 26px;
    margin: 10px;
    flex: 0 0 47%; /* 每个子元素占 50% 的宽度 */
    box-sizing: border-box; /* 防止 padding 和 border 影响宽度 */
  }
  .caseback {
    font-size: 36px;
    color: #ffff;
    position: absolute;
    left: 20px;
  }
  .caseitemname {
    margin: 10px 0;
  }
  .caseicon {
    font-size: 20px;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: absolute;
    right: 25px;
  }

  .caseicon img {
    width: 30px;
    height: 30px;
    margin: 5px 0;
    display: block;
  }
  .caseselect {
    position: absolute;
    right: 25px;
  }
  .ctfiexd {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    background: rgba(0, 0, 0, 0.75);
    z-index: 9999;
  }
  .ctmain {
    width: 304px;
    background-color: #fff;
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 0px;
    right: 0px;
  }
  .cttop {
    font-size: 28px;
    padding: 10px 20px;
    width: 100%;
    margin: 15px 0;
  }
  .closenew {
    width: 40px;
    height: 40px;
    position: absolute;
    right: 20px;
  }
  .ctbox {
    /* background-color: red; */
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
  }
  .ctitem {
    width: 264px;
    height: 70px;
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;

    text-align: center;
    color: #666666;
    margin: 5px auto;
    font-size: 28px;
  }
  .ctitem.active {
    background-color: #5f6d7c;
    color: #ffff;
  }
  .caselistitem {
    width: 690px;
    height: 199px;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    display: flex;
    margin: 11px 0;
    align-items: center;
    padding: 15px;
  }
  .caselistimg {
    width: 170px;
    height: 171px;
    border-radius: 10px;
    overflow: hidden;
    position: relative;
  }
  .caselistimg img {
    width: 170px;
    height: 171px;
  }
  .caselistmain {
    display: flex;
    flex-direction: column;
    padding: 0px 10px;
    width: 485px;
  }
  .caselistdes {
    font-size: 26px;
    color: #666666;
    padding: 10px 0;
    height: 70px;
    width: 485px;
    overflow: hidden; /* 隐藏溢出文本 */
    text-overflow: ellipsis; /* 溢出部分显示省略号 */
    display: -webkit-box; /* 使用弹性盒子模型 */
    -webkit-line-clamp: 2; /* 显示2行，超过2行的部分显示省略号 */
    -webkit-box-orient: vertical; /* 垂直排列子元素 */
    margin: 10px 0;
  }

  .casefavorite img {
    width: 28px;
    height: 26px;
  }
  .caselisttop {
    display: flex;
    font-size: 30px;
    justify-content: space-between;
  }
  .casemains {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    height: 100%;
    padding-bottom: 330px;
    align-items: center;
  }
  .contentd {
    margin: 0 auto;
    background-color: red;
    z-index: 9999;
  }
  .refreshing,
  .loading {
    font-size: 30px;
    color: #bbb4b4;
  }
  .loadingd {
    margin: 50px auto;
    font-size: 30px;
    color: #fff9f9;
  }
  .caseimgqb {
    width: 36px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border-radius: 42px 42px 42px 42px;
    position: absolute;
    top: 5px;
    left: 5px;
    font-size: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #53606f;
  }
  .casetotal {
    width: 29px;
    height: 29px;
    background: #ffffff;
    border-radius: 50%;
    align-items: center;
    display: flex;
    justify-content: center;
    color: #53606f;
    font-size: 18px;
    margin: 0px 10px;
  }
  .casename {
    display: flex;
    align-items: center;
  }
</style>
